import neopixel
import machine
import time
import math
from machine import Pin,PWM
from time import sleep

hPin=27
vPin=26
button=Pin(16,Pin.IN,Pin.PULL_UP)
hJoy= machine.ADC(hPin)
vJoy= machine.ADC(vPin)

LED=Pin(15,Pin.OUT)
buzzer = PWM(Pin(15))
pixPin=0
pixSize=8
bright=1
pix=neopixel.NeoPixel(machine.Pin(pixPin),pixSize)
#pix.fill((100,0,100))
#pix.write()

def getRGB(deg):
    m=1/60
    if deg>=0 and deg<60:
        R=1
        G=0
        B=m*deg
    if deg>=60 and deg<120:
        R=1-m*(deg-60)
        G=0
        B=1
    if deg>=120 and deg<180:
        R=0
        G=m*(deg-120)
        B=1
    if deg>=180 and deg<240:
        R=0
        G=1
        B=1-m*(deg-180)
    if deg>=240 and deg<300:
        R=m*(deg-240)
        G=1
        B=0
    if deg>=300 and deg<360:
        R=1
        G=1-m*(deg-300)
        B=0
    myColor=(int(R*255),int(G*255),int(B*255))
    return myColor

# Note frequencies (Hz)
NOTES = {
    "E7": 2637,
    "C7": 2093,
    "G7": 3136,
    "G6": 1568,
    "E6": 1319,
    "A6": 1760,
    "B6": 1976,
    "AS6": 1865,
    "F7": 2794,
    "D7": 2349,
    "A7": 3520,
    "REST": 0
}

def play_tone(freq, duration):
    if freq == 0:
        buzzer.duty_u16(0)
    else:
        buzzer.freq(freq)
        buzzer.duty_u16(32768)  # 50% duty cycle

    sleep(duration)
    buzzer.duty_u16(0)
    sleep(0.02)

# Mario theme intro
melody = [
    ("E7", 0.12), ("E7", 0.12), ("REST", 0.12),
    ("E7", 0.12), ("REST", 0.12),
    ("C7", 0.12), ("E7", 0.25), 
    ("G7", 0.25), ("REST", 0.25), ("G6", 0.25),("REST", 0.25),

    ("C7", 0.25), ("REST", 0.12),
    ("G6", 0.25), ("REST", 0.12),
    ("E6", 0.25), ("REST", 0.12),

    ("A6", 0.25), ("B6", 0.25),
    ("AS6", 0.12), ("A6", 0.25),

    ("G6", 0.2), ("E7", 0.2),
    ("G7", 0.2), ("A7", 0.25),
    ("F7", 0.12), ("G7", 0.12),

    ("REST", 0.12),
    ("E7", 0.25), ("C7", 0.12),
    ("D7", 0.12), ("B6", 0.25), ("REST", 0.12),

    ("C7", 0.25), ("REST", 0.12),
    ("G6", 0.25), ("REST", 0.12),
    ("E6", 0.25), ("REST", 0.12),

    ("A6", 0.25), ("B6", 0.25),
    ("AS6", 0.12), ("A6", 0.25),

    ("G6", 0.2), ("E7", 0.2),
    ("G7", 0.2), ("A7", 0.25),
    ("F7", 0.12), ("G7", 0.12),

    ("REST", 0.12),
    ("E7", 0.25), ("C7", 0.12),
    ("D7", 0.12), ("B6", 0.25), ("REST", 0.12)
]




while True:
    
        
    hVal=hJoy.read_u16()
    vVal=vJoy.read_u16()
    
    hCal=int(-.00306*hVal+100.766)
    vCal=int(.00306*vVal-100.766)
    
    deg=math.atan2(vCal,hCal)*360/2/math.pi
    if deg<0:
        deg=deg+360
    magMax=math.sqrt(100**2+100**2)
    
    mag=math.sqrt(hCal**2+vCal**2)
    bright=mag/magMax
    if mag<=4:
        hCal=0
        vCal=0
        bright=0
            
    color=getRGB(deg)
    red,green,blue=color
    print(deg,bright)
    pix.fill((int(red*bright),int(green*bright),int(blue*bright)))
    pix.write()
    time.sleep(0.2)

    if button.value()==0: 
        for note, duration in melody:
            play_tone(NOTES[note], duration)
    